package controllers;

import com.fasterxml.jackson.databind.JsonNode;
import com.google.gson.Gson;
import entities.Message;
import helpers.MessageActor;
import play.db.jpa.JPA;
import play.db.jpa.Transactional;
import play.libs.F;
import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Result;
import play.mvc.WebSocket;

import javax.persistence.Query;
import java.util.Calendar;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: eagami
 * Date: 17/05/14
 * Time: 22:45
 * To change this template use File | Settings | File Templates.
 */
public class MessagesController  extends Controller {

    /**
     * Handle the chat websocket.
     */
    public static WebSocket<JsonNode> liveNotifications() {
        return new WebSocket<JsonNode>() {

            // Called when the Websocket Handshake is done.
            public void onReady(WebSocket.In<JsonNode> in, WebSocket.Out<JsonNode> out){

                // Join the chat room.
                try {
                    MessageActor.join(in, out);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        };
    }

    @Transactional
    public static Result getLastTenNotifications() throws Throwable{
        return ok(Json.toJson(getRecentTenNotifications()));
    }

    public static List<MessageActor> getRecentTenNotifications() throws Throwable{
        return JPA.withTransaction(new F.Function0<List<MessageActor>>()  {
            @Override
            public List<MessageActor> apply() throws ClassCastException,Throwable{

                StringBuilder strQuery = new StringBuilder("select distinct m ")

                        .append("from Message m ")
                        .append("order by m.date desc ");

                Query query = JPA.em().createQuery(strQuery.toString());

                return query.setMaxResults(10).getResultList();
            }
        });
    }

    public static Message saveMessage(final String text,final Boolean isNew){
        try {
            return JPA.withTransaction(new F.Function0<Message>() {

                @Override
                public Message apply() throws Throwable {
                    Message m = new Message();
                    m.setDate(Calendar.getInstance().getTime());
                    m.setText(text);
                    m.setIsNew(isNew);

                    m = JPA.em().merge(m);
                    return m;
                }
            });
        } catch (Throwable throwable) {
            throwable.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

        return null;
    }

    @Transactional
    public static Result setOldMessage(){
        JsonNode json = request().body().asJson();
        Gson gson = new Gson();
        if(json.findValue("id") != null){
            StringBuilder strQuery = new StringBuilder("update Message m ")
                    .append("set m.isNew = false ")
                    .append("where m.id = ?1 ");

            Query query = JPA.em().createQuery(strQuery.toString());

            query.setParameter(1, json.findValue("id").asLong());

            query.executeUpdate();
        }

        return ok();
    }

}
